/**
 * 通用工具函数
 */
const log4js = require('./log4j')
const { query } = require('../config/db');
const jwt = require('jsonwebtoken')
const { PRIVATE_KEY, JWT_EXPIRED } = require('../utils/constant')

const CODE = {
  SUCCESS: 200,
  PARAM_ERROR: 10001,//参数错误
  USER_ACCOUNT_ERROR: 20001,//账号或密码错误
  USER_LOGIN_ERROR: 30001,//用户未登录
  BUSINESS_ERROR: 40001,//业务请求失败
  AUTH_ERROR: 50001//认证失败或TOKEN过期
}
module.exports = {
  success(data = '', token = '', msg = '', status = CODE.SUCCESS) {
    log4js.debug(data);
    return {
      status, data, msg, token
    }
  },
  error(msg = '', status = CODE.USER_ACCOUNT_ERROR, data = '') {
    log4js.debug(msg);
    return {
      status, data, msg
    }
  },
  fail(msg = '', status = CODE.BUSINESS_ERROR, data = '') {
    log4js.debug(msg);
    return {
      status, data, msg
    }
  },
  auth(msg = '', status = CODE.AUTH_ERROR, data = '') {
    log4js.debug(msg);
    return {
      status, data, msg
    }
  },
  async login(username, password) {
    try {
      const sql = `select * from users where username='${username}' and password='${password}'`;
      return await query(sql);
    } catch (error) {
      console.log(err);
    }
  },
  // 创建token
  creatToken(res) {
    return jwt.sign(
      { res },
      PRIVATE_KEY,
      { expiresIn: JWT_EXPIRED }
    )
  },
  // 解析token
  decoded(token) {
    if (token.indexOf('Bearer') === 0) {
      token = token.replace('Bearer', '')
    }
    return jwt.verify(token, PRIVATE_KEY)
  }
}